package com.tanhua.management.interceptor;

import cn.hutool.core.util.StrUtil;
import com.tanhua.common.pojo.Manager;
import com.tanhua.management.utils.NoAuthorization;
import com.tanhua.management.service.ManagerService;
import com.tanhua.management.utils.ManagerThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ManagerTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private ManagerService managerService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //放行OPTIONS请求
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }

        //校验handler是否是HandlerMethod
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //判断是否包含@NoAuthorization注解，如果包含，直接放行
        if (((HandlerMethod) handler).hasMethodAnnotation(NoAuthorization.class)) {
            return true;
            //从请求头中获取token

        }

        try {
            //从请求头中获取token
            String token = request.getHeader("Authorization");
            token = token.replace("Bearer ", "");
            if(StrUtil.isNotEmpty(token)){
                Manager manager = managerService.findUserByToken(token);
                if(manager != null){
                    //token有效
                    //将Manager对象放入到ThreadLocal中
                    ManagerThreadLocal.set(manager);
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //token无效，响应状态为401
        response.setStatus(401); //无权限
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //从ThreadLocal中移除Manager对象
        ManagerThreadLocal.remove();
    }
}
